package com.winning.sx.microframework.controller.base;

import com.winning.sx.microframework.common.config.Config;
import com.winning.sx.microframework.common.config.FileUploadConfig;
import net.coobird.thumbnailator.Thumbnails;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("image")
public class ImageController {
    @RequestMapping("upload")
    public void imageUpdate(MultipartHttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String realPath = FileUploadConfig.getUploadNewsImagePath();
        MultiValueMap<String, MultipartFile> files = request.getMultiFileMap();
        response.setContentType("text/plain; charset=UTF-8");
        List<MultipartFile> myfiles = files.get("imgFile");
        PrintWriter out = response.getWriter();
        String originalFilename = null;
        for (MultipartFile myfile : myfiles) {
            if (myfile.isEmpty()) {
                out.print("1请选择文件后上传");
                out.flush();
                out.close();
            } else {
                originalFilename = myfile.getOriginalFilename();
                String fix = originalFilename.substring(originalFilename.lastIndexOf("."));
                String fileName = generateFileName() + fix;
                try {
                    InputStream is = myfile.getInputStream();
                    // 检查上传文件的目录
                    File uploadDir = new File(realPath);
                    if (!uploadDir.isDirectory()) {
                        uploadDir.mkdirs();
                    }
                    FileOutputStream fos = new FileOutputStream(realPath + fileName);
                    byte[] b = new byte[1024];
                    while ((is.read(b)) != -1) {
                        fos.write(b);
                    }
                    is.close();
                    fos.close();

                    BufferedImage sourceImg = ImageIO.read(new FileInputStream(realPath + fileName));
                    int width = sourceImg.getWidth();
                    int height = sourceImg.getHeight();
                    if (width > 600 || height > 600) {
                        Thumbnails.of(realPath + fileName).size(600, 600).toFile(realPath + fileName);
                        sourceImg = ImageIO.read(new FileInputStream(realPath + fileName));
                    }
//					FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, fileName));
                    JSONObject result = new JSONObject();
                    result.put("error", 0);
                    result.put("message", "上传成功");
                    result.put("url", Config.downloadPath + "/" + realPath.substring(realPath.indexOf("upload")) + fileName);
                    result.put("width", sourceImg.getWidth() + "px");// 源图宽度
                    result.put("height", sourceImg.getHeight() + "px"); // 源图高度
                    System.out.println(result.get("url"));
                    out.print(result.toString());
                    out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                    out.print("1文件上传失败，请重试！！！");
                    out.flush();
                } finally {
                    out.close();
                }

            }
        }
        // 读取Excel的数据

    }

    private static String generateFileName() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        int code = (int) (Math.random() * 9000 + 1000);
        return sdf.format(new Date()) + code + "";
    }

    public static void mkdir(String path) {
        File file = new File(path);
        //如果文件夹不存在则创建
        if (!file.exists() && !file.isDirectory()) {
            System.out.println("//不存在");
            if (file.mkdirs()) {
                System.out.println("//已创建");
            } else {
                System.out.println("//无法创建");
            }
        } else {
            System.out.println("//目录存在");
        }
    }

    public static String[] getFullFileName(String type, String folder) {
        String newFileName = generateFileName() + "." + type;
        String realPath = FileUploadConfig.getUploadNewsImagePath() + folder + newFileName;
        String url = Config.downloadPath + "/" + realPath.substring(realPath.indexOf("upload"));
        String ret[] = {realPath, url, null};
        return ret;
    }

    //base64字符串转化成图片
    //对字节数组字符串进行Base64解码并生成图片
    public static boolean GenerateImage(String imgStr, String imgFilePath) throws IOException {
        if (imgStr == null) //图像数据为空  
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream out = null;
        try {
            //Base64解码  
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }
            //生成图片
            mkdir(imgFilePath.substring(0, imgFilePath.lastIndexOf("/")));
            out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            out.close();
        }
    }

    //文件下载
    @RequestMapping("/downLoad")
    public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String path = Config.uploadDiskPath;
        String fileName = request.getParameter("path");
        String name = request.getParameter("name");
        if (name != null) {
            byte[] bt = name.getBytes("ISO-8859-1");
            name = new String(bt, "UTF-8");
        }
        File file = new File(path + "/" + fileName);
        if (file.exists()) {
            String showFileName;
            if (name != null) {
                // 设置下载文件名等
                showFileName = new String(name.replaceAll(" ", "")
                        .getBytes("utf-8"), "iso8859-1");
            } else {
                showFileName = fileName;
            }
            String extName = showFileName.substring(
                    showFileName.lastIndexOf(".")).toLowerCase();
            response.addHeader("Content-Disposition", "attachment;filename="
                    + showFileName);
            response.addHeader("Content-Length", "" + file.length());
            // 设置内容编码
            response.setCharacterEncoding("UTF-8");
            // 设置响应MIME
            if (".doc".equals(extName)) {
                response.setContentType("application/msword");
            } else if (".docx".equals(extName)) {
                response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            } else if (".pdf".equals(extName)) {
                response.setContentType("application/pdf");
            } else if (".xls".equals(extName)) {
                response.setContentType("application/vnd.ms-excel");
            } else if (".xlsx".equals(extName)) {
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            } else if (".ppt".equals(extName)) {
                response.setContentType("application/vnd.ms-powerpoint");
            } else if (".pptx".equals(extName)) {
                response.setContentType("application/vnd.openxmlformats-officedocument.presentationml.presentation");
            } else if (".bmp".equals(extName)) {
                response.setContentType("image/bmp");
            } else if (".gif".equals(extName)) {
                response.setContentType("image/gif");
            } else if (".ief".equals(extName)) {
                response.setContentType("image/ief");
            } else if (".jpeg".equals(extName)) {
                response.setContentType("image/jpeg");
            } else if (".jpg".equals(extName)) {
                response.setContentType("image/jpeg");
            } else if (".png".equals(extName)) {
                response.setContentType("image/png");
            } else if (".tiff".equals(extName)) {
                response.setContentType("image/tiff");
            } else if (".tif".equals(extName)) {
                response.setContentType("image/tif");
            } else if (".txt".equals(extName)) {
                response.setContentType("text/plain");
            }


            InputStream inputStream = new FileInputStream(file);
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] bs = new byte[1024];
            while ((inputStream.read(bs) > 0)) {
                outputStream.write(bs);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
        }
    }
}
